<template>
  <div class="data-overview">
    <div class="overview-content">
      <!-- 数据统计概览 -->
      <div class="stats-overview">
        <div class="stat-card">
          <div class="stat-value">{{ overviewData.total_records }}</div>
          <div class="stat-label">总记录数</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ overviewData.data_quality }}%</div>
          <div class="stat-label">数据质量</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ overviewData.missing_rate }}%</div>
          <div class="stat-label">缺失率</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ overviewData.update_frequency }}</div>
          <div class="stat-label">更新频率</div>
        </div>
      </div>
      
      <!-- 数据时间范围信息 -->
      <div class="time-range-info">
        <div class="time-range-card">
          <div class="time-range-title">
            <Icon type="ios-flash" />
            <span>负荷数据时间范围</span>
          </div>
          <div class="time-range-content">
            <div class="time-item">
              <span class="time-label">开始时间：</span>
              <span class="time-value">{{ loadTimeRange.start_date || '暂无数据' }}</span>
            </div>
            <div class="time-item">
              <span class="time-label">结束时间：</span>
              <span class="time-value">{{ loadTimeRange.end_date || '暂无数据' }}</span>
            </div>
            <div class="time-item">
              <span class="time-label">数据天数：</span>
              <span class="time-value">{{ loadTimeRange.days || 0 }} 天</span>
            </div>
          </div>
        </div>
        
        <div class="time-range-card">
          <div class="time-range-title">
            <Icon type="ios-cloud" />
            <span>气象数据时间范围</span>
          </div>
          <div class="time-range-content">
            <div class="time-item">
              <span class="time-label">开始时间：</span>
              <span class="time-value">{{ weatherTimeRange.start_date || '暂无数据' }}</span>
            </div>
            <div class="time-item">
              <span class="time-label">结束时间：</span>
              <span class="time-value">{{ weatherTimeRange.end_date || '暂无数据' }}</span>
            </div>
            <div class="time-item">
              <span class="time-label">数据天数：</span>
              <span class="time-value">{{ weatherTimeRange.days || 0 }} 天</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 数据分布图表 -->
      <div class="charts-container">
        <div class="chart-section">
          <h4>数据分布统计</h4>
          <div id="distributionChart" style="width: 100%; height: 350px;"></div>
        </div>
        <div class="chart-section">
          <h4>数据质量趋势</h4>
          <div id="qualityChart" style="width: 100%; height: 350px;"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// ECharts 通过全局插件注册，使用 this.$echarts
import { predictionAPI } from '@/utils/api'

export default {
  name: 'DataOverview',
  data() {
    return {
      overviewData: {
        total_records: 0,
        data_quality: 0,
        missing_rate: 0,
        update_frequency: '每日',
        sample_data: []
      },
      loadTimeRange: {
        start_date: '',
        end_date: '',
        days: 0
      },
      weatherTimeRange: {
        start_date: '',
        end_date: '',
        days: 0
      },
      distributionChart: null,
      qualityChart: null,
      loading: false
    }
  },
  mounted() {
    this.initCharts()
    this.loadOverviewData()
  },
  beforeDestroy() {
    if (this.distributionChart) {
      this.distributionChart.dispose()
    }
    if (this.qualityChart) {
      this.qualityChart.dispose()
    }
  },
  methods: {
    async loadOverviewData() {
      try {
        this.loading = true
        console.log('正在加载数据概览信息...')
        
        // 调用数据质量统计API
        const response = await predictionAPI.getDataQualityStats()
        
        if (response.status === 'success' || response.load_stats) {
          const data = response.data || response
          
          // 更新统计数据
          if (data.load_stats) {
            this.overviewData.total_records = data.load_stats.total_records || 0
            this.overviewData.data_quality = data.load_stats.data_completeness || 98.5
            this.overviewData.missing_rate = (100 - (data.load_stats.data_completeness || 98.5)).toFixed(1)
            
            // 更新负荷数据时间范围
            if (data.load_stats.earliest_date && data.load_stats.latest_date) {
              this.loadTimeRange.start_date = this.formatDate(data.load_stats.earliest_date)
              this.loadTimeRange.end_date = this.formatDate(data.load_stats.latest_date)
              this.loadTimeRange.days = this.calculateDays(data.load_stats.earliest_date, data.load_stats.latest_date)
            }
          }
          
          // 更新气象数据时间范围
          if (data.weather_stats) {
            if (data.weather_stats.earliest_date && data.weather_stats.latest_date) {
              this.weatherTimeRange.start_date = this.formatDate(data.weather_stats.earliest_date)
              this.weatherTimeRange.end_date = this.formatDate(data.weather_stats.latest_date)
              this.weatherTimeRange.days = this.calculateDays(data.weather_stats.earliest_date, data.weather_stats.latest_date)
            }
          }
          
          // 更新时间跨度信息
          if (data.time_span) {
            console.log('数据时间跨度:', data.time_span.start_date, '至', data.time_span.end_date)
          }
          
          this.updateCharts()
        }
        
      } catch (error) {
        console.error('加载数据概览失败:', error)
        this.$Message.error('加载数据概览失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },
    
    formatDate(dateStr) {
      if (!dateStr) return ''
      try {
        const date = new Date(dateStr)
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        })
      } catch (error) {
        return dateStr
      }
    },
    
    calculateDays(startDate, endDate) {
      if (!startDate || !endDate) return 0
      try {
        const start = new Date(startDate)
        const end = new Date(endDate)
        const diffTime = Math.abs(end - start)
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
        return diffDays + 1 // 包含开始和结束日期
      } catch (error) {
        return 0
      }
    },
    
    initCharts() {
      // 初始化数据分布统计图表
      this.distributionChart = this.$echarts(document.getElementById('distributionChart'))
      
      const distributionOption = {
        title: {
          text: '数据分布统计',
          textStyle: {
            color: '#bb8fce',
            fontSize: 14
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            return `${params[0].name}<br/>记录数: ${params[0].value}`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['2004年', '2005年', '2006年', '2007年', '2008年'],
          axisLabel: {
            color: '#bb8fce'
          },
          axisLine: {
            lineStyle: {
              color: '#bb8fce'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '记录数',
          nameTextStyle: {
            color: '#bb8fce'
          },
          axisLabel: {
            color: '#bb8fce'
          },
          axisLine: {
            lineStyle: {
              color: '#bb8fce'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#1a3c58'
            }
          }
        },
        series: [
          {
            name: '记录数',
            type: 'bar',
            data: [365, 365, 366, 365, 156],
            itemStyle: {
              color: function(params) {
                const colors = ['#bb8fce', '#af7ac5', '#a569bd', '#9b59b6', '#8e44ad']
                return colors[params.dataIndex]
              }
            },
            label: {
              show: true,
              position: 'top',
              color: '#bb8fce'
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowColor: 'rgba(187, 143, 206, 0.5)'
              }
            }
          }
        ]
      }
      
      this.distributionChart.setOption(distributionOption)
      
      // 初始化数据质量趋势图表
      this.qualityChart = this.$echarts(document.getElementById('qualityChart'))
      
      const qualityOption = {
        title: {
          text: '数据质量趋势',
          textStyle: {
            color: '#bb8fce',
            fontSize: 14
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          formatter: function(params) {
            let result = `月份: ${params[0].axisValue}<br/>`
            params.forEach(param => {
              result += `${param.seriesName}: ${param.value}%<br/>`
            })
            return result
          }
        },
        legend: {
          data: ['数据完整率', '数据准确率'],
          textStyle: {
            color: '#bb8fce'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: Array.from({length: 12}, (_, i) => `${i + 1}月`),
          axisLabel: {
            color: '#bb8fce'
          },
          axisLine: {
            lineStyle: {
              color: '#bb8fce'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '百分比 (%)',
          min: 90,
          max: 100,
          nameTextStyle: {
            color: '#bb8fce'
          },
          axisLabel: {
            color: '#bb8fce'
          },
          axisLine: {
            lineStyle: {
              color: '#bb8fce'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#1a3c58'
            }
          }
        },
        series: [
          {
            name: '数据完整率',
            type: 'line',
            data: this.generateQualityData(98.5),
            itemStyle: {
              color: '#bb8fce'
            },
            lineStyle: {
              width: 3
            },
            smooth: true,
            symbol: 'circle',
            symbolSize: 6
          },
          {
            name: '数据准确率',
            type: 'line',
            data: this.generateQualityData(97.2),
            itemStyle: {
              color: '#8e44ad'
            },
            lineStyle: {
              width: 2,
              type: 'dashed'
            },
            smooth: true,
            symbol: 'diamond',
            symbolSize: 6
          }
        ]
      }
      
      this.qualityChart.setOption(qualityOption)
    },
    
    updateCharts() {
      if (this.distributionChart && this.qualityChart) {
        // 更新图表数据
        const newDistributionData = [365, 365, 366, 365, 156]
        const newQualityData1 = this.generateQualityData(98.5)
        const newQualityData2 = this.generateQualityData(97.2)
        
        this.distributionChart.setOption({
          series: [{
            data: newDistributionData
          }]
        })
        
        this.qualityChart.setOption({
          series: [
            { data: newQualityData1 },
            { data: newQualityData2 }
          ]
        })
      }
    },
    
    generateQualityData(baseValue) {
      // 生成质量趋势数据
      const data = []
      for (let i = 0; i < 12; i++) {
        const variation = Math.sin(i / 6 * Math.PI) * 1.5 + Math.random() * 1 - 0.5
        const value = Math.max(90, Math.min(100, baseValue + variation))
        data.push(Math.round(value * 10) / 10)
      }
      return data
    },
    
    refreshData() {
      this.loadOverviewData()
      this.$Message.success('数据已刷新')
    }
  }
}
</script>

<style lang="less" scoped>
.data-overview {
  width: 100%;
  height: 100%;
  position: relative;
  
  .module-header {
    position: relative;
    margin-bottom: 15px;
    
    .title {
      font-size: 16px;
      font-weight: bold;
      
      .title-gradient {
        background: linear-gradient(45deg, #fd79a8, #6c5ce7);
        -webkit-background-clip: text;
        background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    }
    
    .angle1, .angle2, .angle3, .angle4 {
      position: absolute;
      width: 15px;
      height: 15px;
      border: 2px solid #fd79a8;
    }
    
    .angle1 {
      top: 0;
      left: 0;
      border-right: none;
      border-bottom: none;
    }
    
    .angle2 {
      top: 0;
      right: 0;
      border-left: none;
      border-bottom: none;
    }
    
    .angle3 {
      bottom: 0;
      left: 0;
      border-right: none;
      border-top: none;
    }
    
    .angle4 {
      bottom: 0;
      right: 0;
      border-left: none;
      border-top: none;
    }
  }
  
  .overview-content {
    padding: 15px;
    background: rgba(7, 19, 50, 0.8);
    border: 1px solid #1a3c58;
    border-radius: 8px;
    
    .stats-overview {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
      gap: 15px;
      margin-bottom: 25px;
      
      .stat-card {
        background: rgba(26, 60, 88, 0.4);
        padding: 15px;
        border-radius: 6px;
        border: 1px solid #1a3c58;
        text-align: center;
        
        .stat-value {
          color: #fd79a8;
          font-size: 24px;
          font-weight: bold;
          margin-bottom: 5px;
        }
        
        .stat-label {
          color: #999;
          font-size: 12px;
        }
      }
    }
    
    .time-range-info {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 20px;
      margin-bottom: 25px;
      
      .time-range-card {
        background: rgba(26, 60, 88, 0.4);
        padding: 15px;
        border-radius: 6px;
        border: 1px solid #1a3c58;
        
        .time-range-title {
          display: flex;
          align-items: center;
          margin-bottom: 12px;
          color: #75deef;
          font-size: 14px;
          font-weight: bold;
          
          .ivu-icon {
            margin-right: 8px;
            color: #fd79a8;
          }
        }
        
        .time-range-content {
          .time-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .time-label {
              color: #999;
              font-size: 12px;
            }
            
            .time-value {
              color: #fd79a8;
              font-size: 12px;
              font-weight: bold;
            }
          }
        }
      }
    }
    
    .charts-container {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 20px;
      margin-bottom: 25px;
      
      .chart-section {
        background: rgba(26, 60, 88, 0.4);
        padding: 15px;
        border-radius: 6px;
        border: 1px solid #1a3c58;
        
        h4 {
          color: #75deef;
          margin: 0 0 15px 0;
          font-size: 14px;
          font-weight: bold;
        }
        
        #distributionChart, #qualityChart {
          width: 100%;
          height: 300px; /* Adjust height as needed */
        }
      }
    }
  }
}

// 响应式调整
@media (max-width: 1400px) {
  .data-overview {
    .overview-content {
      .stats-overview {
        grid-template-columns: 1fr 1fr;
      }
      .time-range-info {
        grid-template-columns: 1fr;
      }
      .charts-container {
        grid-template-columns: 1fr;
      }
    }
  }
}

@media (max-width: 800px) {
  .data-overview {
    .overview-content {
      .stats-overview {
        grid-template-columns: 1fr;
      }
      .time-range-info {
        grid-template-columns: 1fr;
      }
    }
  }
}
</style> 